import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt

# 设置显示列和显示宽度
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 500)

# 中文设置
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

# 操作1:音乐器材类商品评分的数据获取
rnames = ['uid', 'pid', 'rating', 'timestamp']
ratings = pd.read_csv('ratings_Musical_Instruments.csv', header=None, names=rnames)
ratings['date'] = ratings['timestamp'].apply(datetime.fromtimestamp)
ratings['year'] = ratings['date'].dt.year
ratings['month'] = ratings['date'].dt.month
print(ratings.head(5))

# # 操作2:音乐器材类商品评分的趋势分析
plt.figure(figsize=(16, 8), dpi=100)

# plt.subplot2grid((2, 2), (0, 0))
# results = ratings[['rating']].groupby(ratings['year']).mean()
# plt.title('商品评分年平均值趋势图')
# plt.plot(results['rating'])
#
# plt.subplot2grid((2, 2), (0, 1))
# results = ratings[['rating']].groupby(ratings['month']).mean()
# plt.title('商品评分月平均值趋势图')
# plt.plot(results['rating'])
#
# plt.subplot2grid((2, 2), (1, 0))
ratings = ratings.set_index('date')
ratings = ratings.to_period(freq='M')
# print(ratings.head(20))
# results = ratings[['rating']].groupby(ratings.index).mean()
# plt.title('商品评分逐年月平均值趋势图')
# plt.plot(results.index.to_timestamp(), results['rating'])
#
# plt.subplot2grid((2, 2), (1, 1))
# results = ratings.groupby(ratings.index)[['rating']].count()
# plt.title('商品评分数量逐月平均值趋势图')
# plt.plot(results.index.to_timestamp(), results['rating'])

# 操作3：多维度的趋势可视化分析
# results = ratings[['rating']].groupby(ratings.index).agg(['mean', 'count'])
# 类似
results = ratings.groupby(ratings.index)['rating'].agg(['mean', 'count'])
print(results)
# plt.scatter(results.index.to_timestamp(), results['mean'], results['count'], c=results['count'], alpha=0.5)

# 将平均评分和评分总数互相交换
plt.subplot2grid((2, 2), (0, 0))
plt.title('评分数量评分均值散点图')
plt.scatter(results.index.to_timestamp(), results['count'], results['mean'], alpha=0.5)

plt.subplot2grid((2, 2), (0, 1))
plt.title('同比例增加散点图中点的大小')
plt.scatter(results.index.to_timestamp(), results['count'], results['mean'] * 1000, alpha=0.2)

plt.subplot2grid((2, 2), (1, 0))
results['newAvg'] = 30 * (results['mean'].max() - results['mean'].min())
results['newAvg'] *= results['newAvg']
plt.scatter(results.index.to_timestamp(), results['count'], results['newAvg'], alpha=0.2)
plt.title('不同比例的增加散点图中点的大小')

plt.subplot2grid((2, 2), (1, 1))
plt.scatter(results.index.to_timestamp(), results['count'], results['newAvg'],c=results['count'], alpha=0.2)
plt.title('增加颜色表示散点图中的大小')

plt.show()